 CREATE FUNCTION dbo.fnProximityGet(@pFromLat AS FLOAT, @pFromLong AS FLOAT, @pToLat AS FLOAT, @pToLong AS FLOAT)
RETURNS FLOAT
AS 

BEGIN
 	DECLARE @TotalDistance 	FLOAT
	DECLARE @ReturnVal 	INT

	SET @ReturnVal = 0

	IF @pFromLat = 0 OR @pFromLong = 0 OR @pToLat = 0 OR @pToLong = 0
		RETURN 222
	 
	IF @pFromLat = @pToLat AND @pFromLong = @pToLong
		RETURN 1
	 
	SET @pFromLat= (PI()/180)*@pFromLat
	SET @pFromLong= (PI()/180)*@pFromLong
	SET @pToLat= (PI()/180)*@pToLat
	SET @pToLong= (PI()/180)*@pToLong
	 
	SET @TotalDistance = POWER(SIN((@pToLat-@pFromLat)/2),2) + COS(@pFromLat) * COS(@pToLat) * POWER(SIN((@pToLong - @pFromLong)/2),2)
	
	SET @TotalDistance = 2 * ATN2(SQRT(@TotalDistance), SQRT(1-@TotalDistance)) 
	
	-- Convert distance into Miles
	SELECT @TotalDistance = 6373 * @TotalDistance * 0.621371 * 1.6
  
	RETURN @TotalDistance
END  
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
